﻿// Decompiled with JetBrains decompiler
// Type: DnProcessSimulateCommands.MovieRecorder.CApMRCRecorderViewModel
// Assembly: DnProcessSimulateCommands, Version=2402.0.0.890, Culture=neutral, PublicKeyToken=null
// MVID: A885D881-AEDF-447E-852A-6F13102E089C
// Assembly location: C:\Program Files\Tecnomatix_2402\eMPower\DotNetCommands\DnProcessSimulateCommands.dll

using DnProcessSimulateCommands.SimulationSettings;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Windows.Forms;
using System.Windows.Media;
using Tecnomatix.Engineering;
using Tecnomatix.Engineering.Ui;


namespace DnProcessSimulateCommands.MovieRecorder;

public class CApMRCRecorderViewModel : INotifyPropertyChanged
{
  private uint _duration;
  private static string DURATION_FORMAT = "hh\\:mm\\:ss";
  private Timer _timer;
  private CApMRCMovieRecorderSceneManager _sceneManager;

  public event EventHandler StopRequested;

  public event EventHandler<DurationChnagedEventArgs> DurationChanged;

  public CApMRCRecorderViewModel()
  {
    this._duration = 0U;
    this.Settings = new CApMRCRecorderSettings();
    this.HasPersistentSettings = true;
    this._timer = new Timer();
    this._timer.Tick += new EventHandler(this._timer_Tick);
    this._timer.Interval = 1000;
    CApMRCCaptureAreaIndicatorManager.Instance.MovieRecordingSourceClosed += new EventHandler(this.Instance_MovieRecordingSourceClosed);
    this._sceneManager = new CApMRCMovieRecorderSceneManager();
  }

  public bool HasPersistentSettings { get; internal set; }

  public CApMRCRecorderViewModel(CApMRCRecorderSettings settings)
    : this()
  {
    this.Settings = settings;
  }

  ~CApMRCRecorderViewModel()
  {
    CApMRCCaptureAreaIndicatorManager.Instance.MovieRecordingSourceClosed -= new EventHandler(this.Instance_MovieRecordingSourceClosed);
  }

  public event PropertyChangedEventHandler PropertyChanged;

  protected virtual void OnPropertyChanged(string propertyName)
  {
    if (this.PropertyChanged == null)
      return;
    this.PropertyChanged((object) this, new PropertyChangedEventArgs(propertyName));
  }

  internal TxMovieRecorder Recorder => TxApplication.MovieRecorder;

  public CApMRCRecorderSettings Settings { get; internal set; }

  public string Duration
  {
    get
    {
      return TimeSpan.FromSeconds((double) this._duration).ToString(CApMRCRecorderViewModel.DURATION_FORMAT);
    }
  }

  public ImageSource SettingsIcon
  {
    get => TxImageManager.GetImageByKey("Settings").ConvertTo<ImageSource>(20U, 20U);
  }

  public ImageSource ActionIcon
  {
    get
    {
      if (!this.IsRecording)
        return TxImageManager.GetImageByKey("Record").ConvertTo<ImageSource>(20U, 20U);
      return this.IsPaused ? TxImageManager.GetImageByKey("Pause").ConvertTo<ImageSource>(20U, 20U) : TxImageManager.GetImageByKey("Resume").ConvertTo<ImageSource>(20U, 20U);
    }
  }

  public ImageSource StopIcon
  {
    get => TxImageManager.GetImageByKey("Stop").ConvertTo<ImageSource>(20U, 20U);
  }

  public ImageSource ResetIcon
  {
    get => TxImageManager.GetImageByKey("Reset").ConvertTo<ImageSource>(20U, 20U);
  }

  public string ActionTooltip
  {
    get
    {
      string actionTooltip = MRCStringTable.MOVIE_RECORDER_RECORD;
      if (this.IsRecording)
        actionTooltip = !this.IsPaused ? MRCStringTable.MOVIE_RECORDER_PAUSE : MRCStringTable.MOVIE_RECORDER_RESUME;
      return actionTooltip;
    }
  }

  public bool IsRecording => this.Recorder.State > 0;

  public bool IsPaused => this.Recorder.State == 2;

  public bool CanChangeSettings => !this.IsRecording;

  public bool DoAction(out string errorMessage)
  {
    bool flag = true;
    if (!this.IsRecording)
    {
      CApMRCCaptureAreaIndicatorManager.Instance.StartRecordingMode();
      flag = this.Start(out errorMessage);
    }
    else if (this.IsPaused)
    {
      CApMRCCaptureAreaIndicatorManager.Instance.StartRecordingMode();
      this.Resume();
      errorMessage = string.Empty;
    }
    else
    {
      this.Pause();
      errorMessage = string.Empty;
      CApMRCCaptureAreaIndicatorManager.Instance.PauseRecordingMode();
    }
    return flag;
  }

  public void Discard()
  {
    if (!this.IsRecording)
      return;
    this._timer.Stop();
    this.Recorder.Terminate();
    CApMRCCaptureAreaIndicatorManager.Instance.EndRecordingMode();
    this.OnPropertyChanged("IsRecording");
    this.OnPropertyChanged("IsPaused");
    this.OnPropertyChanged("ActionIcon");
    this.OnPropertyChanged("ActionTooltip");
    this.OnPropertyChanged("CanChangeSettings");
    this.ResetDuration();
    this.RestoreSimulationTimeInterval();
  }

  public void Stop()
  {
    if (!this.IsRecording)
      return;
    this._timer.Stop();
    this.Recorder.Stop();
    CApMRCCaptureAreaIndicatorManager.Instance.EndRecordingMode();
    this.OnPropertyChanged("IsRecording");
    this.OnPropertyChanged("IsPaused");
    this.OnPropertyChanged("ActionIcon");
    this.OnPropertyChanged("ActionTooltip");
    this.OnPropertyChanged("CanChangeSettings");
    this.ResetDuration();
    this.RestoreSimulationTimeInterval();
  }

  public void LoadSettingsFromXmlString(string xmlStringSettings)
  {
    if (xmlStringSettings != null)
      this.Settings = CApMRCRecorderUtilities.DeserializeSettings(xmlStringSettings);
    this.Settings.Validate();
  }

  public string StoreSettingsToXmlString()
  {
    return CApMRCRecorderUtilities.SerializeSettings(this.Settings);
  }

  public void UpdateScene()
  {
    this._sceneManager.SaveSceneSettings(this.Settings.SceneSettings);
    this._sceneManager.SetSceneVisibility(this.Settings.SceneSettings);
  }

  public void RestoreOriginalScene() => this._sceneManager.RestoreOriginalScene();

  private bool Start(out string errorMessage)
  {
    bool flag = true;
    string str = string.Empty;
    errorMessage = string.Empty;
    try
    {
      string fileFullName = this.Settings.GetFileFullName(true);
      TxMovieRecordingSettings recordingSettings;
      if (this.Settings.ScreenCaptureArea == CaptureArea.Screen)
      {
        recordingSettings = (TxMovieRecordingSettings) new TxScreenRecordingSettings(fileFullName, this.Settings.GetScreenCaptureRect());
      }
      else
      {
        this.ChangeSimulationTimeInterval();
        recordingSettings = (TxMovieRecordingSettings) new TxViewerRecordingSettings(fileFullName, CApMRCCaptureAreaIndicatorManager.Instance.MovieRecordingViewerSource, this.Settings.ResolutionWidth, this.Settings.ResolutionHeight);
        ((TxViewerRecordingSettings) recordingSettings).TimeSource = this.Settings.TimeSource;
      }
      recordingSettings.FrameRate = this.Settings.FrameRate;
      recordingSettings.Compression = this.Settings.Compression;
      recordingSettings.Codec = this.Settings.Codec;
      recordingSettings.AddOverlays(this.CreateOverlays());
      this.Recorder.Start(recordingSettings);
      this._timer.Start();
    }
    catch (TxNoWritePermissionOnFolderException ex)
    {
      flag = false;
      str = string.Format(MRCStringTable.MOVIE_RECORDER_NO_WRITE_PERMISSIONS, (object) this.Settings.FileDestination);
    }
    catch (TxInvalidPathException ex)
    {
      flag = false;
      str = string.Format(MRCStringTable.MOVIE_RECORDER_DIRECTORY_NOTFOUND, (object) this.Settings.FileDestination);
    }
    catch (TxMovieRecorderException ex)
    {
      flag = false;
      str = ex.ErrorMessage;
      if (!TxMovieRecordingSettings.GetSupportedCodecs().Any<TxVideoCodec>((Func<TxVideoCodec, bool>) (x => x == this.Settings.Codec)))
        str = MRCStringTable.MOVIE_RECORDER_CODEC_NOT_FOUND;
    }
    catch (TxArgumentOutOfRangeException ex)
    {
      flag = false;
      str = MRCStringTable.MOVIE_RECORDER_SCREEN_CAPTURE_RANGE;
    }
    catch
    {
      flag = false;
    }
    this.OnPropertyChanged("IsRecording");
    this.OnPropertyChanged("IsPaused");
    this.OnPropertyChanged("ActionIcon");
    this.OnPropertyChanged("ActionTooltip");
    this.OnPropertyChanged("CanChangeSettings");
    if (!flag)
    {
      errorMessage = MRCStringTable.MOVIE_RECORDER_START_FAILED;
      if (!string.IsNullOrEmpty(str))
        errorMessage = errorMessage + Environment.NewLine + str;
    }
    return flag;
  }

  private void Pause()
  {
    this._timer.Stop();
    this.Recorder.Pause();
    this.OnPropertyChanged("IsPaused");
    this.OnPropertyChanged("ActionIcon");
    this.OnPropertyChanged("ActionTooltip");
    this.OnPropertyChanged("CanChangeSettings");
  }

  private void Resume()
  {
    this._timer.Start();
    this.Recorder.Resume();
    this.OnPropertyChanged("IsPaused");
    this.OnPropertyChanged("ActionIcon");
    this.OnPropertyChanged("ActionTooltip");
    this.OnPropertyChanged("CanChangeSettings");
  }

  private void UpdateDuration()
  {
    uint duration = this.Recorder.Duration;
    if ((int) this._duration == (int) duration)
      return;
    this._duration = duration;
    this.OnPropertyChanged("Duration");
    if (this.DurationChanged == null)
      return;
    this.DurationChanged((object) this, new DurationChnagedEventArgs()
    {
      CurrentDuration = this.Duration
    });
  }

  private void ResetDuration()
  {
    this._duration = 0U;
    this.OnPropertyChanged("Duration");
  }

  private void Instance_MovieRecordingSourceClosed(object sender, EventArgs e)
  {
    if (!this.IsRecording || this.StopRequested == null)
      return;
    this.StopRequested((object) this, new EventArgs());
  }

  private void _timer_Tick(object sender, EventArgs e) => this.UpdateDuration();

  internal void UpdateIndicator()
  {
    CApMRCCaptureAreaIndicatorManager.Instance.Update(this.Settings);
  }

  internal void CloseIndicator() => CApMRCCaptureAreaIndicatorManager.Instance.Close();

  private void ChangeSimulationTimeInterval()
  {
    if (this.Settings.TimeIntervalAccordingFrameRate <= 0.0)
      return;
    if (!TxApplication.ActiveDocument.SimulationPlayer.IsSimulationRunning())
    {
      CSISSimulationSettingsManager.SetTemporaryTimeInterval(this.Settings.TimeIntervalAccordingFrameRate);
    }
    else
    {
      int num = (int) TxMessageBox.ShowModal(MRCStringTable.MOVIE_RECORDER_CHANGE_SIM_TIME_INTERVAL, MRCStringTable.MOVIE_RECORDER_COMMAND_NAME, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
    }
  }

  private void RestoreSimulationTimeInterval()
  {
    if (this.Settings.TimeSource != 1 || !this.Settings.ChangeSimulationTimeInterval)
      return;
    CSISSimulationSettingsManager.ResetTemporaryTimeInterval();
  }

  private List<TxMovieOverlay> CreateOverlays()
  {
    List<TxMovieOverlay> overlays = new List<TxMovieOverlay>();
    if (this.Settings.OverlayImagePath != string.Empty)
      overlays.Add((TxMovieOverlay) new TxMovieImageOverlay(this.Settings.OverlayImagePath, this.Settings.OverlayImageWidth.Percent(this.Settings.OverlayImageSizePercent), this.Settings.OverlayImageHeight.Percent(this.Settings.OverlayImageSizePercent), this.Settings.OverlayImageTransparency, this.Settings.OverlayPosition));
    if (this.Settings.OverlayText != string.Empty)
      overlays.Add((TxMovieOverlay) new TxMovieTextOverlay(this.Settings.OverlayText, this.Settings.OverlayFontSize, this.Settings.ToColor(this.Settings.OverlayFontColor), this.Settings.ToColor(this.Settings.OverlayFontShadowColor), this.Settings.OverlayPosition));
    return overlays;
  }
}
